<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php

class CCharacter
{


    
    public static function getChineseCount($s){
        return preg_match_all("/[\xB0-\xF7][\xA1-\xFE]/", $str,$str);
    }

    
    public static function IsAllChinese($s){
        return preg_match("/^[xb0-xf7][xa0-xfe]+$/",$str);
    }

    
    public static function checkIsChinese($s){
        return preg_match('/[\x80-\xff]./', $s);
    }

    
    public static function gbStrlen($str){
        $count = 0;
        for($i=0; $i<strlen($str); $i++){
            $s = substr($str, $i, 1);
            if (preg_match("/[\x80-\xff]/", $s)) ++$i;
            ++$count;
        }
        return $count;
    }

    
    public static function gbSubstr($str, $len){
        $count = 0;
        for($i=0; $i<strlen($str); $i++){
            if($count == $len) break;
            if(preg_match("/[\x80-\xff]/", substr($str, $i, 1))) ++$i;
            ++$count;
        }
        return substr($str, 0, $i);
    }

    
    public static function utf8Strlen($str) {
        $count = 0;
        for($i = 0; $i < strlen($str); $i++){
            $value = ord($str[$i]);
            if($value > 127) {
                $count++;
                if($value >= 192 && $value <= 223) $i++;
                elseif($value >= 224 && $value <= 239) $i = $i + 2;
                elseif($value >= 240 && $value <= 247) $i = $i + 3;
                else die('Not a UTF-8 compatible string');
            }
            $count++;
        }
        return $count;
    }


    
    public static function utf8Substr($str,$position,$length){
        $start_position = strlen($str);
        $start_byte = 0;
        $end_position = strlen($str);
        $count = 0;
        for($i = 0; $i < strlen($str); $i++){
            if($count >= $position && $start_position > $i){
                $start_position = $i;
                $start_byte = $count;
            }
            if(($count-$start_byte)>=$length) {
                $end_position = $i;
                break;
            }
            $value = ord($str[$i]);
            if($value > 127){
                $count++;
                if($value >= 192 && $value <= 223) $i++;
                elseif($value >= 224 && $value <= 239) $i = $i + 2;
                elseif($value >= 240 && $value <= 247) $i = $i + 3;
                else die('Not a UTF-8 compatible string');
            }
            $count++;

        }
        return(substr($str,$start_position,$end_position-$start_position));
    }
}